import { ScrollView, View } from "@tarojs/components";
import { getOptionIndex } from "@/utils";
import {
  useState,
  useRef,
  useEffect,
  forwardRef,
  useImperativeHandle,
} from "react";
import { ScrollPickerProps } from "@/types";
import "./index.less";

const ScrollPicker = forwardRef(
  ({ value, options, itemHeight = 38 }: ScrollPickerProps, ref) => {
    const initIndex = getOptionIndex(value, options);
    const [selectedIndex, setSelectedIndex] = useState<number>(initIndex);
    const scrollRef = useRef<any>(null);

    useImperativeHandle(ref, () => ({
      getValue: () => options[selectedIndex].value,
    }));

    const handleScroll = (e) => {
      const { scrollTop } = e.detail;
      const index = Math.round(scrollTop / itemHeight);
      const validIndex = Math.min(Math.max(index, 0), options.length - 1);
      if (validIndex !== selectedIndex) {
        setSelectedIndex(validIndex);
      }
    };

    useEffect(() => {
      if (scrollRef.current) {
        scrollRef.current.props.scrollTop = initIndex * itemHeight;
      }
    }, []);

    return (
      <ScrollView
        style={{ height: `${itemHeight * 4}px` }}
        scrollY
        className="scroll-picker"
        scrollWithAnimation
        onScroll={handleScroll}
        ref={scrollRef}
      >
        <View className="scroll-picker-options">
          {options.map((item, index) => (
            <View
              key={item.value}
              style={{
                height: `${itemHeight}px`,
                lineHeight: `${itemHeight}px`,
              }}
              className={`option-item ${
                index === selectedIndex ? "active" : ""
              }`}
            >
              {item.label}
            </View>
          ))}
        </View>
      </ScrollView>
    );
  }
);

export default ScrollPicker;
